import {ref, watch} from 'vue';
import {io} from 'socket.io-client'
import storage from "@/utils/storage";

export function useSocket() {
    const socket = ref()

    function emit(url, params, callback) {
        const m_u = `controller.${url}`
        console.log(socket.value)
        socket.value.emit('c1', {cmd: m_u, params}, (res) => {
            callback && callback(res)
        })
    }
    function on(name,callback) {
        socket.value.on(name, (res) => {
            callback && callback(res)
        })
    }
    function conn() {
        let userInfo = storage.get('userInfo')
        userInfo = userInfo ? JSON.parse(userInfo) : {}
        const url = `ws://127.0.0.1:7070?user_id=${userInfo.id}`
        socket.value = io(url, {transports: ["websocket"]});
        socket.value.on('connect', () => {
            console.log('链接成功');
        });
    }

    return {
        socket,
        on,
        emit,
        conn
    }
}